<template>
  <div class="nifti-slicer-container">
    <a-typography-title :heading="2" style="text-align: center; margin-bottom: 20px;">
      3D医学影像切片处理
    </a-typography-title>

    <a-card class="upload-section">
      <template #title>
        <div class="section-title">
          <icon-upload />
          <span>上传NIfTI文件</span>
        </div>
      </template>

      <a-form :model="formData" layout="vertical">
        <a-form-item field="file" label="NIfTI文件">
          <a-upload
            :custom-request="handleUpload"
            :limit="1"
            :file-list="fileList"
            @change="handleFileChange"
            accept=".nii,.nii.gz"
            :drag="true"
          >
            <template #upload-button>
              <div class="upload-area">
                <div class="upload-icon">
                  <icon-file-image :style="{ fontSize: '48px', color: 'rgb(var(--primary-6))' }" />
                </div>
                <div class="upload-text">
                  <p>点击或拖拽NIfTI文件到此处上传</p>
                  <p class="upload-hint">支持.nii和.nii.gz格式的3D医学影像</p>
                </div>
              </div>
            </template>
          </a-upload>
        </a-form-item>

        <a-divider />
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="orientation" label="切片方向">
              <a-radio-group v-model="formData.orientation" type="button">
                <a-radio value="axial">轴位 (Axial)</a-radio>
                <a-radio value="sagittal">矢状位 (Sagittal)</a-radio>
                <a-radio value="coronal">冠状位 (Coronal)</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="format" label="输出格式">
              <a-radio-group v-model="formData.format" type="button">
                <a-radio value="png">PNG</a-radio>
                <a-radio value="jpg">JPG</a-radio>
                <a-radio value="bmp">BMP</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="normalize">
              <a-checkbox v-model="formData.normalize">标准化图像</a-checkbox>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="enhance">
              <a-checkbox v-model="formData.enhance">增强图像</a-checkbox>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item>
          <a-button type="primary" :loading="isProcessing" :disabled="!fileList.length" @click="startProcessing">
            开始切片处理
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <div class="processing-status" v-if="isProcessing">
      <a-spin tip="正在处理中，请稍候..." />
    </div>

    <div class="result-section" v-if="processResult">
      <a-card>
        <template #title>
          <div class="section-title">
            <icon-apps />
            <span>切片结果 (共 {{ processResult.total_slices }} 张)</span>
          </div>
        </template>

        <a-alert type="success" :content="processResult.message" banner />

        <div class="slice-controls">
          <a-space>
            <a-button type="outline" @click="currentSliceIndex = 0">首张</a-button>
            <a-button type="outline" @click="prevSlice" :disabled="currentSliceIndex <= 0">
              <icon-left />上一张
            </a-button>
            <a-input-number v-model="currentSliceIndex" :min="0" :max="processResult.total_slices - 1" style="width: 100px" />
            <span>/</span>
            <span>{{ processResult.total_slices - 1 }}</span>
            <a-button type="outline" @click="nextSlice" :disabled="currentSliceIndex >= processResult.total_slices - 1">
              下一张<icon-right />
            </a-button>
            <a-button type="outline" @click="currentSliceIndex = processResult.total_slices - 1">末张</a-button>
          </a-space>
        </div>

        <div class="slice-viewer">
          <a-image v-if="currentSliceUrl" :src="currentSliceUrl" :alt="`切片 ${currentSliceIndex + 1}`" fit="contain" />
        </div>

        <a-divider />

        <a-collapse>
          <a-collapse-item header="查看所有切片" key="1">
            <div class="slice-gallery">
              <a-row :gutter="[16, 16]">
                <a-col :span="4" v-for="(slice, index) in processResult.slices" :key="index">
                  <div 
                    class="slice-thumbnail" 
                    :class="{ active: currentSliceIndex === index }" 
                    @click="currentSliceIndex = index"
                  >
                    <a-image :src="slice" :alt="`切片 ${index + 1}`" />
                    <span class="slice-number">{{ index + 1 }}</span>
                  </div>
                </a-col>
              </a-row>
            </div>
          </a-collapse-item>

          <a-collapse-item header="下载选项" key="2">
            <a-space direction="vertical" style="width: 100%">
              <a-button type="outline" @click="downloadCurrentSlice" :disabled="!currentSliceUrl">
                <template #icon><icon-download /></template>
                下载当前切片
              </a-button>
              <a-button type="primary" @click="downloadAllSlices" status="success">
                <template #icon><icon-download /></template>
                下载全部切片
              </a-button>
            </a-space>
          </a-collapse-item>
        </a-collapse>
      </a-card>
    </div>

    <a-modal v-model:visible="errorVisible" @cancel="errorVisible = false" title="处理失败" simple>
      <div class="error-content">
        <a-result status="error" :title="errorMessage" />
      </div>
      <template #footer>
        <a-button @click="errorVisible = false">关闭</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { Message } from '@arco-design/web-vue';
import { 
  IconUpload, 
  IconFileImage, 
  IconLeft, 
  IconRight, 
  IconDownload, 
  IconApps
} from '@arco-design/web-vue/es/icon';
import { niftiApi } from '@/services/api';

// 表单数据
const formData = reactive({
  orientation: 'axial',
  normalize: false,
  enhance: false,
  format: 'png'
});

// 上传文件相关
const fileList = ref<any[]>([]);
const handleFileChange = (files: any) => {
  fileList.value = files;
};

// 处理状态
const isProcessing = ref(false);
const processResult = ref<any>(null);
const errorVisible = ref(false);
const errorMessage = ref('处理失败，请稍后重试');

// 当前查看的切片
const currentSliceIndex = ref(0);
const currentSliceUrl = computed(() => {
  if (!processResult.value || !processResult.value.slices || processResult.value.slices.length === 0) {
    return '';
  }
  return processResult.value.slices[currentSliceIndex.value];
});

// 切片导航
const nextSlice = () => {
  if (processResult.value && currentSliceIndex.value < processResult.value.total_slices - 1) {
    currentSliceIndex.value++;
  }
};

const prevSlice = () => {
  if (currentSliceIndex.value > 0) {
    currentSliceIndex.value--;
  }
};

// 上传处理
const handleUpload = (options: any) => {
  const { onSuccess } = options;
  // 只是通知上传组件文件已接收，实际处理在startProcessing中进行
  onSuccess();
};

// 开始处理
const startProcessing = async () => {
  if (!fileList.value.length) {
    Message.warning('请先上传NIfTI文件');
    return;
  }

  try {
    isProcessing.value = true;

    const result = await niftiApi.splitNifti(fileList.value[0].file, {
      orientation: formData.orientation,
      normalize: formData.normalize,
      enhance: formData.enhance,
      format: formData.format
    });

    processResult.value = result;
    currentSliceIndex.value = 0;
    Message.success(result.message);
  } catch (error: any) {
    console.error('处理失败:', error);
    errorMessage.value = error.message || '处理失败，请稍后重试';
    errorVisible.value = true;
    processResult.value = null;
  } finally {
    isProcessing.value = false;
  }
};

// 下载当前切片
const downloadCurrentSlice = () => {
  if (currentSliceUrl.value) {
    const link = document.createElement('a');
    link.href = currentSliceUrl.value;
    link.download = `slice_${currentSliceIndex.value + 1}.${formData.format}`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
};

// 下载所有切片
const downloadAllSlices = () => {
  if (processResult.value && processResult.value.output_dir) {
    // 这里简单处理，实际应该使用web API或后端提供zip下载
    window.open(processResult.value.output_dir, '_blank');
    Message.info('请在打开的页面中右键保存所需切片');
  }
};
</script>

<style scoped>
.nifti-slicer-container {
  padding: var(--spacing-xl);
  max-width: 1200px;
  margin: 0 auto;
}

.section-title {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  font-weight: 500;
  font-size: 16px;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  border: 2px dashed var(--color-border-2);
  border-radius: var(--radius-md);
  transition: all 0.2s ease;
}

.upload-area:hover {
  border-color: rgb(var(--primary-6));
  background-color: rgb(var(--primary-1));
}

.upload-text {
  margin-top: var(--spacing-lg);
  text-align: center;
}

.upload-hint {
  font-size: 12px;
  color: var(--color-text-3);
  margin-top: 8px;
}

.result-section {
  margin-top: var(--spacing-xl);
}

.processing-status {
  display: flex;
  justify-content: center;
  margin: var(--spacing-xl) 0;
}

.slice-controls {
  display: flex;
  justify-content: center;
  margin: var(--spacing-lg) 0;
}

.slice-viewer {
  display: flex;
  justify-content: center;
  margin: var(--spacing-lg) 0;
  background-color: var(--color-fill-2);
  border-radius: var(--radius-md);
  padding: var(--spacing-lg);
  height: 400px;
}

.slice-gallery {
  margin-top: var(--spacing-lg);
}

.slice-thumbnail {
  position: relative;
  cursor: pointer;
  border-radius: var(--radius-sm);
  overflow: hidden;
  border: 2px solid transparent;
  transition: all 0.2s;
}

.slice-thumbnail.active {
  border-color: rgb(var(--primary-6));
  box-shadow: 0 0 8px rgba(var(--primary-6), 0.4);
}

.slice-thumbnail:hover {
  transform: translateY(-2px);
}

.slice-number {
  position: absolute;
  bottom: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 2px 6px;
  font-size: 12px;
  border-top-left-radius: var(--radius-sm);
}

:deep(.arco-image) {
  width: 100%;
  height: 100%;
}

:deep(.arco-image-img) {
  object-fit: contain;
}

:deep(.slice-viewer .arco-image) {
  height: 100%;
}
</style> 